package com.destinomusical.epura.adapter;

//Need the following import to get access to the app resources, since this
//class is in a sub-package.
import java.io.InputStream;
import java.net.URL;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.androidquery.AQuery;
import com.destinomusical.epura.img.ImageLoader;
import com.destinomusical.epura.obj.Categoria;
import com.smartthinking.destinomusical.R;

public class CatListAdapter extends BaseAdapter {
	private Context mContext;
	List<?> mdataObjectList;
	private LayoutInflater inflater;
	AQuery aq;
//	public ImageLoader imageLoader;
	
	public CatListAdapter(Activity a, List<?> dataObjectList) {
		mContext = a.getApplicationContext();
		mdataObjectList = dataObjectList;
		inflater = (LayoutInflater) a
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		aq = new AQuery(mContext);
//		imageLoader = new ImageLoader(a.getApplicationContext());
	}

	@Override
	public int getCount() {
		return mdataObjectList.size();
	}

	@Override
	public Object getItem(int position) {
		return mdataObjectList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	public void deleteItem(int position) {
		mdataObjectList.remove(position);
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		Categoria obj = (Categoria) mdataObjectList.get(position);
	    String url = obj.getImgURL().replaceAll(" ", "%20");
	    Log.i("URL", ""+url);
		View vi = convertView;
		final ViewHolder holder;

		if (vi == null) {
			vi = inflater.inflate(R.layout.listitem_catego, null);
			holder = new ViewHolder();
			holder.imagen = (ImageView) vi.findViewById(R.id.image);
			vi.setTag(holder);
		} else {
			holder = (ViewHolder) vi.getTag();
		}
		holder.imagen.setTag(url);
		
		aq.id(holder.imagen).image(url); 
//		imageLoader.DisplayImage(holder.imagen.getTag().toString(),
//				 holder.imagen);
		return vi;
	}

	public static class ViewHolder {
		public ImageView imagen;
	}
	
	public void clearCache(){
//		imageLoader.clearCache();
	}


	public static Drawable LoadImageFromWebOperations(String url) {
		try {
			InputStream is = (InputStream) new URL(url).getContent();
			Drawable d = Drawable.createFromStream(is, "src name");
			return d;
		} catch (Exception e) {
			return null;
		}
	}
}